﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class SiteMaster : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ddlCompID.DataBind();
            BindMenu();

            //Logger.WriteLog(Page.AppRelativeVirtualPath);
            
            if (CheckAuth() == false)
            {
                Response.Redirect(FormsAuthentication.DefaultUrl);
            }
        }
    }

    protected void ddlCompID_SelectedIndexChanged(object sender, EventArgs e)
    {
        OrgManager.Current.CurrentComp = ddlCompID.Text;
    }

    DataTable _MenuData;

    DataTable MenuData
    {
        get
        {
            if (_MenuData == null)
            {
                var db = new DB();

                _MenuData = db.Execute(string.Format("SELECT * FROM Func WHERE FuncID IN ({0}) AND Status = 'Y' ",
                                        MyObj.JoinFormat(",", "{0}", RoleManager.Current.GetFuncsForUser())));

                LocManager.Current.Translate(_MenuData, "Func", "FuncName");
            }

            return _MenuData;
        }
    }

    protected void BindMenu()
    {
        mv.Items.Clear();

        foreach (DataRow dr in MenuData.Select("[Parent]=0"))
        {
            var mi = new MenuItem();

            mi.Value = dr["FuncID"].ToString();
            mi.Text = dr["FuncName"].ToString();
            mi.NavigateUrl = dr["Url"].ToString();

            mv.Items.Add(mi);

            BindMenuRec(mi);
        }
    }

    protected void BindMenuRec(MenuItem parent)
    {
        foreach (DataRow dr in MenuData.Select("[Parent]=" + parent.Value))
        {
            var mi = new MenuItem();

            mi.Value = dr["FuncID"].ToString();
            mi.Text = dr["FuncName"].ToString();
            mi.NavigateUrl = dr["Url"].ToString();

            parent.ChildItems.Add(mi);

            BindMenuRec(mi);
        }
    }

    protected bool CheckAuth()
    {
        var db = new DB();

        var dr = db.ExecuteRow(@"SELECT f.* FROM func f WHERE @Url LIKE Url + '%' AND LEN(URL) > 0", new DBParameter("Url", Page.AppRelativeVirtualPath));

        if (dr == null) // public page
        {
            return true;
        }
        else
        {
            return RoleManager.Current.GetFuncsForUser().Contains((int)dr["FuncID"]);
        }
    }
}
